package com.dingding.configuration;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dingding.entity.UserSession;
import com.dingding.utils.SessionUserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserSession user = SessionUserUtil.get();
        if (Objects.nonNull(user)) {
            this.setFieldValByName("updatedBy", user.getUserName(), metaObject);
            this.setFieldValByName("createdBy", user.getUserName(), metaObject);
        }
        this.setFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("createdTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserSession user = SessionUserUtil.get();
        if (Objects.nonNull(user)) {
            this.setFieldValByName("updatedBy", user.getUserName(), metaObject);
        }
        this.setFieldValByName("updatedTime", LocalDateTime.now(), metaObject);
    }
}
